package org.dfl.data;

import java.io.File;

import org.dfl.log.Logger;

/**
 *
 * @author Lukas
 */
public class Repository {

    private static final String APPNAME = "dfl_designer";
    private static final String HOME_PROP = "tavernalc.home";
    private static Repository instance = null;

    protected Repository() {
        findHomeDir();
    }

    public static Repository getInstance() {
        try {
            if (instance == null) {
                instance = new Repository();
            }
        } catch (Exception ex) {
            Logger.logException(ex);
        }

        return instance;
    }

    private void findHomeDir() {
        File appHome;
        String application = APPNAME;
        String tavHome = System.getProperty(HOME_PROP);
        if (tavHome != null) {
            appHome = new File(tavHome);
        } else {
            File home = new File(System.getProperty("user.home"));
            if (!home.isDirectory()) {
                return;
            }
            String os = System.getProperty("os.name");
            if (os.equals("Mac OS X")) {
                File libDir = new File(home, "Library/Application Support");
                libDir.mkdirs();
                appHome = new File(libDir, application);
            } else if (os.startsWith("Windows")) {
                String APPDATA = System.getenv("APPDATA");
                File appData = null;
                if (APPDATA != null) {
                    appData = new File(APPDATA);
                }
                if (appData != null && appData.isDirectory()) {
                    appHome = new File(appData, application);
                } else {
                    appHome = new File(home, application);
                }
            } else {
                // We'll assume UNIX style is OK
                appHome = new File(home, "." + application.toLowerCase());
            }
        }
        if (!appHome.exists()) {
            if (appHome.mkdir()) {
            } else {
                System.clearProperty(HOME_PROP);
                return;
            }
        }
        if (!appHome.isDirectory()) {
            System.clearProperty(HOME_PROP);
            return;
        }

        System.setProperty(HOME_PROP, appHome.getAbsolutePath());
        return;
    }

    public File getHomeFile() {
        return new File(System.getProperty(HOME_PROP));
    }
}
